<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图片上传</title>
<style>
    .uploadImgBtn {
        width: 100px;
        height: 100px;
        cursor: pointer;
        position: relative;
        background: url("img/plus.png") no-repeat;
        -webkit-background-size: cover;
        background-size: cover;
    }

    .uploadImgBtn .uploadImg {
        position: absolute;
        right: 0;
        top: 0;
        width: 100%;
        height: 100%;
        opacity: 0;
        cursor: pointer;
    }

    .pic {
        width: 100px;
        height: 100px;
    }

    .pic img {
        width: 100%;
        height: 100%;
    }
</style>
<script>
    $(document).ready(function(){
        $("#file1").on("change", upload );
    })

    function upload(){
        /**
         * 我们存一下this对象，
         * 我们将在ajax的回调函数中，
         * 将要用这个对象，
         * 用它来改变父盒子的背景图
         *
         */
        var self = this;
        //如果不理解我写的，可以看看我的前几篇文章
        $.ajax({
            url: "/UpImg/upload",
            type: "post",
            dataType: "json",
            cache: false,
            data: new FormData($("#formTag1")[0]),
            processData: false,// 不处理数据
            contentType: false, // 不设置内容类型
            success: function(data){
                /*
                    后端返回的数据格式为
                    {"url": "xxxxxx"}
                 */
                $(self).parent().css({
                    "background-image": "url("+data.url+")"
                })
            }

        })
    }

</script>
</head>
<body>
<div id="formBox">
    <form id="formTag1" enctype="multipart/form-data">
        <div class="uploadImgBtn" id="uploadImgBtn">
            <input class="uploadImg" type="file" name="file" id="file1">
        </div>
    </form>
</div>
</body>
</html>